//
//  UIViewController+Extension.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/5/22.
//

import Foundation

// MARK: - 视频通话
extension UIViewController {
    
    /// 验证 我自己的积分是否满足拨打电话
    func checkVideoCallScore(userId: String, isTranslation: Bool) {
        let target = FreightForwardingAPI.getVideoCallScore(from: String(UserProfile.userId), to: userId)
        YLRequest.request(target) { result in
            switch result {
            case .success(let res):
                if let flag = res.dataDictionary["flag"] as? Int {
                    if flag == 1 {
                        // 可以视频通话
                        self.checkIsLiving(userId: userId, isTranslation: isTranslation)
                        
                    } else {
                        YLHUD.hideHUD()
                        // 积分不足,弹提示框
                        self.scoreNotEnough()
                    }
                }
                
            case .failure(let err):
                YLHUD.showHint(.error, err.errMsg)
            }
        }
    }
    
    /// 判断对方是不是正在直播
    /// - Parameters:
    ///   - conversationID: 用户 id
    func checkIsLiving(userId: String, isTranslation: Bool) {
        let target = LiveAPI.checkIsLiving(userId: userId)
        YLRequest.request(target) { result in
            switch result {
            case .success(let res):
                
                if let roomId: String = res.dataDictionary["roomId"] as? String, !roomId.isEmpty {
                    // 直播中
                    YLHUD.showHint(.warning, "当前用户正忙，请稍后再拨。".localized(.call))
                    
                } else {
                    // 未开直播
                    self.videoChatUserInfo(userId, isTranslation: isTranslation)
                }
                
            case .failure(_):
                YLHUD.hideHUD()
            }
        }
    }
    
    /// 视频通话,获取用户信息
    /// - Parameters:
    ///   - userId: 用户 id
    func videoChatUserInfo(_ userId: String, isTranslation: Bool) {
        MineMainViewModel.loadUserInfo(userId) { userModel in
            YLHUD.hideHUD()
            guard let userModel = userModel else { return }
            self.videoCall(userId: String(userId), userName: userModel.username, avatar: userModel.avatar, isTranslation: isTranslation)
        }
    }
    
    /// 视频通话
    /// - Parameters:
    ///   - userId: 用户 id
    ///   - userName: 用户昵称
    ///   - avatar: 头像
    ///   - isTranslation: true：需要翻译，false：不需要
    func videoCall(userId: String, userName: String, avatar: String, isTranslation: Bool) {
        // 呼叫id 格式call_%@_%ld
        ZegoUIKitPrebuiltCallInvitationService.shared.callID = "call_\(UserProfile.userId)_\(Date.sg.timestamp())"
        // 邀请用户
        let callUser = ZegoPluginCallUser(userID: userId, userName: userName, avatar: avatar)
        // 推送信息配置 "gluz_call_resources" 固定管理后台配置好了
        let notificationConfig = ZegoSignalingPluginNotificationConfig(resourceID: "gluz_call_resources")
        
        // 通话邀请
        // 直播间邀请翻译的时候， customerData 传 223
        // 视频通话需要翻译的时候， customerData = 1
        // 不需要翻译传 0
        ZegoUIKitPrebuiltCallInvitationService.shared.sendInvitation([callUser], invitationType: .videoCall, timeout: 60, customerData: isTranslation ? "1": "0", notificationConfig: notificationConfig) { data in
            xLog("sendInvitation \(data! as NSDictionary)")
        }
    }
    
    /// 积分不足,弹提示框
    func scoreNotEnough() {
        YLAlert(controller: self, title: "提示".localized(), message: "由于积分不足，无法发送IM消息，如您需要继续服务，请及时充值积分，给您带来的不便我们深表歉意。".localized(), actionTitles: ["去充值".localized()]) { [weak self] action, index in
            let url = SystemEnvManager.shared.forwarderUrl + "/pages/vip/scorePoint?" + H5UrlManager.urlParameter()
            let vc = BaseWebViewController(url: url, isNavBarHide: true)
            self?.push(vc)
        }
    }
}
